package com.gaoyi.crm.activity;

import androidx.activity.result.ActivityResult;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.gaoyi.crm.R;
import com.gaoyi.crm.activity.base.BaseActivity;
import com.gaoyi.crm.constant.Constants;
import com.gaoyi.crm.constant.SPName;
import com.gaoyi.crm.databinding.ActivityLoginBinding;
import com.gaoyi.crm.db.bean.Event;
import com.gaoyi.crm.util.NetworkUtil;
import com.gaoyi.crm.util.PermissionUtils;
import com.gaoyi.crm.util.SPUtil;
import com.gaoyi.crm.util.ToastUtil;
import com.gaoyi.crm.vm.LoginViewModel;

import java.util.Map;

public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginViewModel> {

    @Override
    protected void event(Event event) {

    }

    @Override
    protected void onRequestPermissionsResult(Map<String, Boolean> result) {
    }

    @Override
    protected void onActivityResult(int requestCode, ActivityResult result) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {
        mPermissionsResult = registerForPermissionsResult();
        PermissionUtils.addPermission(this, new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        }, mPermissionsResult);
        mViewModel.setName(SPUtil.getInstance().getString(SPName.USER));
        mBinding.btnLogin.setOnClickListener(this::login);
        mViewModel.getLoginResultCode().observe(this,integer -> mBinding.btnLogin.setEnabled(true));
    }

    private void login(View v) {
        if (TextUtils.isEmpty(mViewModel.getName().getValue())) {
            ToastUtil.showToast(R.string.username_hint);
            return;
        }
        String pwd = mViewModel.getPassword().getValue();
        if (TextUtils.isEmpty(pwd)) {
            ToastUtil.showToast(R.string.pw_hint);
            return;
        }
        if (NetworkUtil.isConnected()) {
            v.setEnabled(false);
            mViewModel.login(pwd);
        }else {
            ToastUtil.showToast(R.string.network_error);
        }
    }
}